import java.util.ArrayDeque;
import java.util.Deque;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 前序遍历二叉树
 * 非递归实现
 * User: xwl
 * Date: 2023-05-22
 * Time: 22:37
 */



public class Test3 {
    // 节点类
    class TreeNode3 {
        int val;
        TreeNode3 left;
        TreeNode3 right;
        TreeNode3() {}
        TreeNode3(int val) { this.val = val; }
        TreeNode3(int val, TreeNode3 left, TreeNode3 right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 前序遍历二叉树（非递归）
     * @param root
     */
    public void preorder(TreeNode3 root) {
        // 讨论树为空的情况
        if (root == null) {
            return;
        }
        // 创建一个节点用来存当前节点
        TreeNode3 cur = root;
        // 创建一个栈来存放节点
        Deque<TreeNode3> stack = new ArrayDeque<>();
        // 实现
        while (cur != null || !stack.isEmpty()) {
            // 判断
            while (cur != null) {
                stack.push(cur);
                System.out.println(cur.val + " ");
                cur = cur.left;
            }
            // 定义一个top来表示当前弹出的元素
            TreeNode3 top = stack.pop();
            cur = top.right;
        }
    }
}
